package org.example.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class SmsSendingUtils {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private Client smsClient;

//    @Value("${aliyun.sms.sms-sign-name}")
    private String signName = "积云AI对话";


//    @Value("${aliyun.sms.sms-template-code}")
    private String smsCodeTemplateCode = "SMS_474045018";

    public void sendCode(String phone) {
        //生成验证码
        Random random = new Random();
        int ran = random.nextInt(9000) + 1000;
        String code = String.valueOf(ran);
        System.out.println("生成的验证码为：++++++++++++++++"+code);
        //将验证码存入redis
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        //发送手机验证码
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        System.out.println("添加的手机号码是：++++++++++++++++"+sendSmsRequest.getPhoneNumbers());
        sendSmsRequest.setSignName(signName);
        sendSmsRequest.setTemplateCode(smsCodeTemplateCode);
        Map<String, String> templateParams = new HashMap<>();
        templateParams.put("code", code);
        sendSmsRequest.setTemplateParam(JSONUtil.toJsonStr(templateParams));
        try {
            SendSmsResponse sendSmsResponse = smsClient.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
            // 200为成功
            SendSmsResponseBody body = sendSmsResponse.getBody();
            // code和message为OK成功
            String codes = body.getCode();
            String message = body.getMessage();
            if (StrUtil.equals("OK", codes) && StrUtil.equals("OK", message)) {
                log.info("向 手机号：{} 用户发送短信验证码成功！", phone);
            } else {
                log.warn("向 手机号：{} 用户发送短信验证码失败！", phone);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
